package com.yricky.memoria.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.pdf.PdfRenderer
import android.os.ParcelFileDescriptor
import java.io.File

/**
 * @author Yricky
 * @date 2021/12/7
 */
class PdfDoc private constructor(val pdfFile: File) {

    companion object{
        fun from(pdfFile:File):PdfDoc?{
            if(!pdfFile.exists()){
                return null
            }
            return try{
                PdfDoc(pdfFile)
            }catch (e:Throwable){
                null
            }
        }
    }

    private val render:PdfRenderer? = try{
        PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY))
    }catch (e:Throwable){
        null
    }

    val pageCount get() = render?.pageCount ?: 0

    fun getPage(pageIndex:Int,maxWidth:Int,maxHeight:Int,useBitmap:(Bitmap)->Unit){
        Executor.execUrgency{
            synchronized(this){
                render?.openPage(pageIndex)?.use {
                    val bitmap = if(maxWidth*1f/maxHeight > it.width*1f/it.height){
                        val w = it.width*1f/it.height*maxHeight
                        Bitmap.createBitmap(w.toInt(),maxHeight,Bitmap.Config.ARGB_8888)
                    }else{
                        val h = it.height*1f/it.width*maxWidth
                        Bitmap.createBitmap(maxWidth,h.toInt(),Bitmap.Config.ARGB_8888)
                    }
                    val canvas:Canvas = Canvas(bitmap)
                    canvas.drawRGB(0xff,0xff,0xff)
                    it.render(bitmap,null,null,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    mainThreadHandler.post {
                        useBitmap(bitmap)
                    }
                }
            }
        }
    }

}